package c.francis.interceptor;

import c.francis.pojo.Member;
import c.francis.service.impl.MemberServiceImpl;
import c.francis.utils.CookieUtils;
import c.francis.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private MemberServiceImpl   memberService;

    @Autowired
    private HostHolder  hostHolder;


    //在访问Controller之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取ticket凭证
        String ticket = CookieUtils.getValue(request, "ticket");
        //System.out.println("---------访问Controller之前的拦截器");
        if (ticket != null) {
//            查询用户
            Member member = memberService.findMemberByTicket(ticket);
            hostHolder.setUser(member);
        }

        return true;
//        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    //在访问Controller之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

        Member user = hostHolder.getUser();
        //System.out.println("---------访问Controller之后的拦截器"+user);

        if (user != null && modelAndView!=null) {
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        hostHolder.clear();
    }
}
